<template>
  <div>
    <el-dialog title="发布卖单" v-model="editVisible" width="780px" top="5vh" :close-on-click-modal="false"
      @close="handleclose">
      <el-form>
        <!-- label="选择碳票"  -->
        <el-form-item :required="true">
          <!-- <el-table
              :data="tableData"
              border
              class="table"
              style="width: 90%"
              ref="multipleTable"
              header-cell-class-name="table-header"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" label="全选" width="55">
              </el-table-column>

              <el-table-column
                prop="principalPeople"
                label="持有者"
              ></el-table-column>
              <el-table-column
                prop="serialNumber"
                label="编号"
              ></el-table-column>
              <el-table-column
                prop="location"
                label="项目地址"
              ></el-table-column>
              <el-table-column
                prop="area"
                label="项目面积（亩）"
              ></el-table-column>
              <el-table-column prop="alreadyUsedCarbon" label="碳排放量（吨）">
                <template #default="scope">
                  {{
                    Number(scope.row.monitorCarbonReduction) -
                    Number(scope.row.alreadyUsedCarbon)
                  }}
                </template>
              </el-table-column>
              <el-table-column
                prop="recordNumber"
                label="备案号"
              ></el-table-column>
            </el-table> -->
          <!-- <div class="pagination">
              <el-pagination
                background
                layout="total, prev, pager, next"
                :current-page="seachfrom.pageNum"
                :page-size="seachfrom.pageSize"
                :total="pageTotal"
                @current-change="handlePageChange"
              ></el-pagination>
            </div> -->
          <div>
            <el-row :gutter="22" class="demo-autocomplete text-center margintop30">
              <el-col :span="10">
                <div class="sub-title my-2 text-sm text-gray-600">
                  <span class="fontSize20">*碳排放量</span>
                  <span class="describe_name">含手续费（吨）</span>
                </div>
                <el-input placeholder="请输入碳排放量" v-model="add_from.amount" type="number"
                  @blur="handleAountBlur"></el-input>
                <div class="describe_name" style="color: #01957d; margin-top: 10px">
                  可交易碳量：{{ Carbon_balance.usableCarbon }}吨
                </div>
              </el-col>
              <el-col :span="10">
                <div class="sub-title my-2 text-sm text-gray-600">
                  <div style="display: flex; align-items: center">
                    <el-popover placement="bottom" :width="500" trigger="click">
                      <template #reference>
                        <div class="cursorp">
                          <span class="fontSize20">*实际挂单</span>
                          <i class="el-alert__icon el-icon-warning"></i>
                        </div>
                      </template>
                      <el-form :inline="true" class="demo-form-inline">
                        <el-form-item label="交易手续费"> {{ tradingRateValue }}%</el-form-item>
                        <!-- <div v-for="(item, index) in TradingList" :key="index">
                          <div class="display-space-between">
                            <el-form-item :label="'第' + Number(index + 1) + '档'">
                              <div class="displayflex">
                                <el-input placeholder="" disabled v-model="item.smallValue"></el-input>~
                                <el-input placeholder="" disabled v-model="item.bigValue">
                                  <template #append>吨 </template>
                                </el-input>
                              </div>
                            </el-form-item>
                            <el-form-item label="，手续费">
                              <el-input placeholder="" disabled v-model="item.tradeFees"></el-input>
                            </el-form-item>
                          </div>
                        </div> -->
                      </el-form>
                    </el-popover>
                  </div>
                </div>
                <el-input placeholder="实际挂单" disabled v-model="add_from.actual_amount"></el-input>
              </el-col>
              <el-col :span="4" style="display: flex;align-items: center; ">
                <div class="sub-title my-2 text-sm text-gray-600">
                  <div style="display: flex; align-items: center">
                    <el-popover placement="bottom" :width="200" trigger="click">
                      <template #reference>
                        <div class="cursorp">
                          <el-checkbox v-model="add_from.saleMethod" :true-label="1" :false-label="0" label="整单出售"
                            size="large" />
                          <i class="el-alert__icon el-icon-warning"></i>
                        </div>
                      </template>
                      <el-form :inline="true" class="">
                        <div class="">
                          勾选此项后，买方必须整单购买该订单所有碳量。
                        </div>
                      </el-form>
                    </el-popover>
                  </div>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="22" class="demo-autocomplete text-center margintop30">
              <el-col :span="12">
                <div class="sub-title my-2 text-sm text-gray-600">
                  <span class="fontSize20">*单价</span>
                  <span class="describe_name">系统建议价格参考，可自行编辑</span>
                </div>
                <el-input placeholder="请输入单价" v-model="add_from.price" @blur="handleEntrusted">
                  <template #append>元</template></el-input>
              </el-col><el-col :span="12">
                <div class="sub-title my-2 text-sm text-gray-600">
                  <span class="fontSize20">*售价</span>
                  <span class="describe_name">系统建议价格参考，可自行编辑</span>
                </div>
                <el-input placeholder="售价" disabled v-model="add_from.entrustedprice">
                  <template #append>元</template></el-input>
              </el-col>
            </el-row>
            <el-row :gutter="21" class="text-center margintop30">
              <el-col :span="23">
                <div class="sub-title my-2 text-sm text-gray-600">
                  <span class="fontSize20">*联系电话</span>
                </div>
                <div class="displayflex align-items">
                  <el-input placeholder="联系电话" v-model="add_from.phone" :disabled="!is_modification">
                    <template #append v-if="!is_modification">
                      <span @click="handleModification" class="cursorp">修改</span>
                    </template></el-input>
                  <el-input placeholder="请输入验证码" v-model="add_from.code" v-if="is_modification">
                    <template #append>
                      <span class="cursorp" v-show="showtime" @click="sendCode()">{{ count }}</span>
                      <span class="cursorp" v-show="!showtime" @click="sendCode()">重新发送（{{ count }}s）</span>
                    </template></el-input>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="21" class="text-center margintop30">
              <el-col :span="23">
                <div class="sub-title my-2 text-sm text-gray-600">
                  <span class="fontSize20">*收款方式</span>
                </div>
                <div class="display-space-between">
                  <el-select placeholder="请选择收款方式" v-model="add_from.accountPaymentId">
                    <el-option v-for="item in bankList" :key="item.id" :label="item.paymentType" :value="item.id">
                    </el-option>
                  </el-select>
                  <div class="setStyle" @click="handleSetPaymentTerm">设置</div>
                </div>
              </el-col>
            </el-row>
          </div>
          <div>
            <el-checkbox v-model="add_from.is_read" size="large"></el-checkbox>

            我已阅读并同意林业碳汇认定流转平台
            <span class="blue cursorp" @click="handleAgreement(1)">《服务协议》 </span><span class="blue cursorp"
              @click="handleAgreement(2)">《隐私保护政策》</span>
          </div>
          <div class="btn_b">
            <el-button @click="handleclose" class="icon-search1">取消</el-button>
            <el-button type="primary" class="icon-search" @click="handleSaveEdit">确定</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer> </template>
    </el-dialog>
  </div>
</template>
<script>
import { ref, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getRemainCarbon } from "../assets/js/dictionaries";
import api from "../api/api";
export default {
  components: {},
  setup(props, context) {
    console.log(context);
    // 参考图片
    var userInfojson = localStorage.getItem("userInfo");
    const userInfo = JSON.parse(userInfojson);
    const editVisible = ref(context.attrs.editVisible);
    const radioValue = ref(context.attrs.radioValue);
    const router = useRouter();
    const handleclose = () => {
      editVisible.value = false;
      context.emit("handleclose", editVisible.value);
    };
    const seachfrom = reactive({
      certificateNumber: null,
      registerNumber: null,
      woodlandUsePeople: null,
      woodlandRightPeople: null,
      pageNum: 1,
      pageSize: 8,
    });
    const add_from = reactive({
      carbonIds: [],
      amount: null,
      actual_amount: null,
      price: null,
      phone: userInfo.phone,
      entrustedprice: null,
      is_read: false,
      accountPaymentId: null,
      code: null,
      saleMethod: 0,
    });
    const tableData = ref([]);
    const pageTotal = ref(0);
    const SelectList = ref([]);
    const is_modification = ref(false);
    const count = ref("点击获取验证码");
    const showtime = ref(true);
    // 获取表格数据
    const getData = () => {
      api
        .getListAPI("carbon/client/carbon/getTradeCarbon", seachfrom)
        .then((res) => {
          if (res.data.code == 1) {
            for (var i = 0; i < res.data.data.length; i++) {
              res.data.data[i].checked = false;
            }
            tableData.value = res.data.data;
            pageTotal.value = res.data.data.total || 0;
          } else {
            ElMessage.error(res.data.message);
          }
          //数据处理
        })
        .catch((err) => {
          console.log(err);
        });
    };
    // getData();
    const tradingRate = ref("");
    const tradingRateValue = ref("");
    const getConfigValue = () => {
      api
        .getListAPI(
          "trade/client/trade/config/getConfigValue/TRANSACTION_FEES_PERCENTAGE",
          {}
        )
        .then((res) => {
          if (res.data.code == 1) {
            tradingRate.value = res.data.data;
            let serviceChargeRate = res.data.data * 100;
            // 百分比带有小数点则保留两位小数
            if ((serviceChargeRate + '').indexOf('.') != -1) {
              tradingRateValue.value = (serviceChargeRate).toFixed(2);
            } else {
              tradingRateValue.value = serviceChargeRate;
            }
          } else {
            ElMessage.error(res.data.message);
          }
          //数据处理
        })
        .catch((err) => {
          console.log(err);
        });
    };
    getConfigValue();
    const bankList = ref([]);
    const getbankList = () => {
      api
        .getListAPI("trade/client/account/payment/getDetail", {})
        .then((res) => {
          if (res.data.code == 1) {
            if (res.data.data) {
              bankList.value = [res.data.data];
            }
          } else {
            ElMessage.error(res.data.message);
          }
          //数据处理
        })
        .catch((err) => {
          console.log(err);
        });
    };
    getbankList();
    // 查询操作
    const handleSearch = () => {
      seachfrom.pageNum = 1;
      getData();
    };
    const emptySearch = () => {
      seachfrom.pageNum = 1;
      seachfrom.registerNumber = null;
      seachfrom.certificateNumber = null;
      seachfrom.woodlandRightPeople = null;
    };
    const handleSelect = (res) => {
      console.log(res);
    };
    const handleSaveEdit = () => {
      if (!add_from.amount) {
        ElMessage.error("请输入碳需求量");
        return;
      } else if (!add_from.price) {
        ElMessage.error("请输入单价");
        return;
      } else if (is_modification == true && !add_from.code) {
        ElMessage.error("请输入验证码");
        return;
      } else if (!add_from.accountPaymentId) {
        ElMessage.error("请选择收款方式");
        return;
      } else if (!add_from.is_read) {
        ElMessage.error("请勾选同意协议");
        return;
      }

      for (var i = 0; i < selectList.value.length; i++) {
        add_from.carbonIds.push(selectList.value[i].id);
      }

      context.emit("handleSaveEdit", add_from);
    };
    const handleAgreement = (index) => {
      console.log(index);
      router.push("./agreement");
    };
    const handleModification = () => {
      is_modification.value = true;
    };
    const timer = ref(null);
    // 获取验证码
    const sendCode = () => {
      // if (!form.moblie) {
      //   ElMessage.success("请输入手机号");
      // } else if (!telStr.test(form.moblie)) {
      //   ElMessage.error("请输入正确的手机号");
      //   return;
      // } else {
      let TIME_count = 60;
      if (!timer.value) {
        count.value = TIME_count;
        showtime.value = false;
        api
          .postFormAPI(
            "auth/client/account/getSupplyPhoneCode/" + add_from.phone
          )
          .then((res) => {
            console.log(res);
            if (res.data.code == 1) {
              ElMessage.success("验证码已发送");
              timer.value = setInterval(() => {
                if (count.value > 0 && count.value <= TIME_count) {
                  count.value--;
                } else {
                  showtime.value = true;
                  clearInterval(timer.value);
                  timer.value = null;
                }
              }, 1000);
            } else {
              ElMessage.error(res.data.message);
            }
          })
          .catch((err) => console.log(err));
      }
      // }
    };
    const handleSetPaymentTerm = () => {
      router.push("./receivingSet");
    };
    const Carbon_balance = ref({});
    getRemainCarbon().then((res) => {
      console.log(res);
      Carbon_balance.value = res;
    });
    const handleAountBlur = () => {
      if (add_from.amount > Carbon_balance.value.usableCarbon) {
        ElMessage.error("输入的碳量不大于可用碳量");
        return;
      }
      real_cancelled();
    };
    const real_cancelled = () => {
      // for (var i = 0; i < TradingList.value.length; i++) {
      //   if (
      //     add_from.amount >= TradingList.value[i].smallValue &&
      //     add_from.amount <= TradingList.value[i].bigValue
      //   ) {
      //     add_from.actual_amount = (
      //       Number(add_from.amount) - Number(TradingList.value[i].tradeFees)
      //     ).toFixed(2);
      //   }
      // }
      add_from.actual_amount = (
        Number(add_from.amount) - (Number(add_from.amount) * tradingRate.value)
      ).toFixed(2);
      if (add_from.price) {
        add_from.entrustedprice = (
          Number(add_from.price) * Number(add_from.amount)
        ).toFixed(2);
      }
    };
    const selectList = ref([]);
    const handleSelectionChange = (selectArr) => {
      console.log(selectArr);
      selectList.value = selectArr;
      add_from.amount = null;
      for (var i = 0; i < selectArr.length; i++) {
        add_from.amount += Number(selectArr[i].monitorCarbonReduction);
      }
      real_cancelled();
    };
    const handleEntrusted = () => {
      add_from.entrustedprice = (
        Number(add_from.price) * Number(add_from.amount)
      ).toFixed(2);
    };
    return {
      add_from,
      selectList,
      router,
      radioValue,
      editVisible,
      tableData,
      seachfrom,
      pageTotal,
      count,
      showtime,
      timer,
      SelectList,
      is_modification,
      tradingRateValue,
      bankList,
      Carbon_balance,
      sendCode,
      handleclose,
      handleSearch,
      emptySearch,
      handleSelect,
      handleSaveEdit,
      handleAgreement,
      handleModification,
      handleSetPaymentTerm,
      handleSelectionChange,
      handleAountBlur,
      handleEntrusted,
    };
  },
};
</script>

<style lang="less" scoped>
@import "../assets/css/common.css";
@import "../assets/css/common.less";

&:deep(.el-dialog) {
  box-shadow: none;
}

&:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #909399;
  background: #fff;
  width: 30px;
  height: 30px;
  border-radius: 360px;
  font-size: 30px;
}

.btn_b {
  margin-top: 40px;
}

.container {
  border: 0px;
}

.content_info>div {
  margin-top: 20px;
}

.el-input__inner {
  width: 100% !important;
  border-radius: 0 !important;
}

&:deep(.el-input__inner) {
  border-radius: 0 !important;
}

.demo-autocomplete {
  margin-right: 20px;
  padding-right: 30px;
}

.el-select {
  width: 90%;
}
</style>
